/**
 * Author:  Lgh.
 * Date:    2018/8/24.
 * File：   post公共处理.
 * 说明： 后端响应格式为 {status：‘’， data: {}, msg: ''}
 * 其中data为对象或数组, status: 200成功，400失败
 */

import * as axios from 'axios'
import Qs from 'qs'
import config from '../config'
import * as utils from '../utils'
import 'mint-ui/lib/style.css'
import {Toast} from 'mint-ui'
import router from '@/router'

const instance = axios.create({
  baseURL: config.website + '/mobile',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  },
  dataType: 'jsonp',
  transformResponse: [function (data) {
    try {
      data = JSON.parse(data)
    } catch (e) {
      console.error('请求到的数据不是json格式', data)
    }
    return data
  }],
  transformRequest: [function (data) {
    data = Qs.stringify(data)
    return data
  }]
})

async function post (url, param) {
  let token = ''
  token = token === '' ? utils.getCookie('token') : token
  param = param || {}
  param.token = token // token
  return new Promise((resolve, reject) => {
    instance.post(url, param).then(function (response) {
      response = response.data
      if (response.status === 200) {
        resolve(response.data)
      } else {
        // reject(response.msg)
        if (response.data === 'url_to_login') {
          Toast('登录超时，请重新登录')
          utils.setCookie('token', '', -1)
          router.push({name: 'passport-login'})
        } else {
          Toast(response.msg)
        }
      }
    }).catch(e => {
      console.error('请求发生错误', e)
    })
  })
}

export default post
